package com.youlai.boot.factory.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.youlai.boot.auth.model.dto.WxMiniAppCodeLoginDTO;
import com.youlai.boot.common.constant.SystemConstants;
import com.youlai.boot.core.security.extension.wx.WxMiniAppCodeAuthenticationToken;
import com.youlai.boot.core.security.model.AuthenticationToken;
import com.youlai.boot.core.security.model.UserAuthCredentials;
import com.youlai.boot.core.security.token.TokenManager;
import com.youlai.boot.core.security.util.ExternalSecurityUtils;
import com.youlai.boot.core.security.util.SecurityUtils;
import com.youlai.boot.system.model.dto.CurrentUserDTO;
import com.youlai.boot.system.model.entity.User;
import com.youlai.boot.system.model.entity.UserRole;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.factory.mapper.FactoryMemberMapper;
import com.youlai.boot.factory.service.FactoryMemberService;
import com.youlai.boot.factory.model.entity.FactoryMember;
import com.youlai.boot.factory.model.form.FactoryMemberForm;
import com.youlai.boot.factory.model.query.FactoryMemberQuery;
import com.youlai.boot.factory.model.vo.FactoryMemberVO;
import com.youlai.boot.factory.converter.FactoryMemberConverter;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import org.springframework.transaction.annotation.Transactional;

/**
 * 服装厂员工信息服务实现类
 *
 * @author youlaitech
 * @since 2025-09-28 21:51
 */
@Service
@RequiredArgsConstructor
public class FactoryMemberServiceImpl extends ServiceImpl<FactoryMemberMapper, FactoryMember> implements FactoryMemberService {

    private final FactoryMemberConverter factoryMemberConverter;

    /**
     * 获取服装厂员工信息分页列表
     *
     * @param queryParams 查询参数
     * @return {@link IPage<FactoryMemberVO>} 服装厂员工信息分页列表
     */
    @Override
    public IPage<FactoryMemberVO> getFactoryMemberPage(FactoryMemberQuery queryParams) {
        Page<FactoryMemberVO> pageVO = this.baseMapper.getFactoryMemberPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }

    /**
     * 获取服装厂员工信息表单数据
     *
     * @param id 服装厂员工信息ID
     * @return 服装厂员工信息表单数据
     */
    @Override
    public FactoryMemberForm getFactoryMemberFormData(Long id) {
        FactoryMember entity = this.getById(id);
        return factoryMemberConverter.toForm(entity);
    }

    /**
     * 新增服装厂员工信息
     *
     * @param formData 服装厂员工信息表单对象
     * @return 是否新增成功
     */
    @Override
    public boolean saveFactoryMember(FactoryMemberForm formData) {
        FactoryMember entity = factoryMemberConverter.toEntity(formData);
        return this.save(entity);
    }

    /**
     * 更新服装厂员工信息
     *
     * @param id       服装厂员工信息ID
     * @param formData 服装厂员工信息表单对象
     * @return 是否修改成功
     */
    @Override
    public boolean updateFactoryMember(Long id, FactoryMemberForm formData) {
        FactoryMember entity = factoryMemberConverter.toEntity(formData);
        return this.updateById(entity);
    }

    /**
     * 删除服装厂员工信息
     *
     * @param ids 服装厂员工信息ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteFactoryMembers(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的服装厂员工信息数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }


    /**
     * 根据OpenID获取用户认证信息
     *
     * @param openId 微信OpenID
     * @return 用户认证信息
     */
    @Override
    public FactoryMember getAuthCredentialsByOpenId(String openId) {
        if (StrUtil.isBlank(openId)) {
            return null;
        }
        return this.baseMapper.getAuthCredentialsByOpenId(openId);
    }


    /**
     * 注册或绑定微信用户
     *
     * @param openId 微信OpenID
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean registerOrBindWechatUser(String openId) {
        if (StrUtil.isBlank(openId)) {
            return false;
        }

        // 查询是否已存在该openId的用户
        FactoryMember existMember = this.getOne(
                new LambdaQueryWrapper<FactoryMember>()
                        .eq(FactoryMember::getOpenId, openId)
        );

        if (existMember != null) {
            // 用户已存在，不需要注册
            return true;
        }

        // 创建新用户
        FactoryMember newFactoryMember = new FactoryMember();
        newFactoryMember.setName("微信用户");  // 默认昵称
        newFactoryMember.setOpenId(openId);
        newFactoryMember.setGender(0); // 保密
        newFactoryMember.setUpdateBy(SecurityUtils.getUserId());
        newFactoryMember.setCreateTime(LocalDateTime.now());
        newFactoryMember.setUpdateTime(LocalDateTime.now());
        this.save(newFactoryMember);
        return true;
    }


    /**
     * 获取登录用户信息
     *
     * @return {@link CurrentUserDTO}   用户信息
     */
    @Override
    public FactoryMember getCurrentUserInfo() {
        ExternalSecurityUtils.getFactoryMemberId();

        FactoryMember factoryMember = this.getOne(new LambdaQueryWrapper<FactoryMember>().eq(FactoryMember::getId, ExternalSecurityUtils.getFactoryMemberId()));
        return factoryMember;
    }
}
